import { reactive } from 'vue'
import { Page, CustomEnum } from 'custom/index'

export default class FormPage extends Page {
  private groupId = 0;
  public static name: CustomEnum = 'FormPage';

  protected static props = {
    data: {
      type: Object,
      default: () => ({})
    },
    getApi: {
      type: Object,
      default: () => Promise.resolve({})
    },
    addApi: {
      type: Object,
      default: () => Promise.resolve(null)
    },
    editApi: {
      type: Object,
      default: () => Promise.resolve(null)
    },
    getDefaultData: null
  }

  protected slots: { [key in CustomEnum]?: string }  = {
    AuthButtonGroup: 'auth-button'
  }

  private _getApi: (value?: any, row?: any) => Promise<any> = (_, row) => Promise.resolve(row)
  public getApi(api: any) {
    this._getApi = api
    return this
  }

  private _getDefaultData: (value?: any, row?: any) => any;
  public getDefaultData(api: any) {
    this._getDefaultData = api
    return this
  }

  // private _editApi: (params?: any) => Promise<any> = () => Promise.resolve(null)
  // public editApi(api: any) {
  //   this._editApi = api
  //   return this
  // }

  // private _addApi: (params?: any) => Promise<any> = () => Promise.resolve(null)
  // public addApi(api: any) {
  //   this._addApi = api
  //   return this
  // }

  private _postApi: (params?: any) => Promise<any> = () => Promise.resolve(null)
  public postApi(api: any) {
    this._postApi = api
    return this
  }

  useGroup(title = '') {
    const group = this.add('FormPageGroup', `FormPageGroup-${++this.groupId}`)
    group._props.title = title
    return group
  }
  addGroup(title = '') {
    this.useGroup(title)
    return this
  }

  useAuthButton() {
    const authBtn = this.add('AuthButtonGroup')
    return authBtn
  }
  addAuthButton() {
    this.useAuthButton()
    return this
  }

  setData(prop: string, value: any) {
    ;(this.instance.$refs.custom as any).data[prop] = value
    return this
  }

  protected get props() {
    const query = {}
    const formItems = this.getAll('FormPageFormItem')
    formItems.forEach(item => {
      Object.assign(query, item.propsValue)
    })
    const data = reactive<any>(query)
    return {
      data: data,
      getApi: this._getApi,
      postApi: this._postApi,
      getDefaultData: this._getDefaultData
    }
  }
}
